import type { MaybeRefOrGetter } from 'vue'

export function useTableErrorCell(
  tableRef: MaybeRefOrGetter<any>,
) {
  const errorDestructionFunc: Map<
    `${number}_${number}`,
    (() => any)[]
  > = new Map()

  const errorCell = (
    rowIndex: number,
    colIndex: number,
    errorMessage: string = '',
  ) => {
    const key: `${number}_${number}` = `${rowIndex}_${colIndex}`
    const func = toValue(tableRef).errorCell(
      rowIndex,
      colIndex,
      errorMessage,
    )
    let m = errorDestructionFunc.get(key)
    if (!m) {
      const n = [] as any
      errorDestructionFunc.set(key, n)
      m = n
    }
    m!.push(func)
  }

  const removeError = (
    rowIndex: number,
    colIndex: number,
    // errorMessage: string = ''
  ) => {
    const key: `${number}_${number}` = `${rowIndex}_${colIndex}`
    const m = errorDestructionFunc.get(key)
    // errorDestructionFunc.forEach(f => f?.());
    m?.forEach?.(f => f?.())
    m?.length && (m.length = 0)
  }
  const isExistError = (
    rowIndex: number,
    colIndex: number,
  ) => {
    const key: `${number}_${number}` = `${rowIndex}_${colIndex}`
    const m = errorDestructionFunc.get(key)
    return !!m
  }

  const clearError = () => {
    // console.log('调用了');

    const fs = [...errorDestructionFunc.values()]
    fs.forEach((m) => {
      m?.forEach?.(f => f?.())
      m?.length && (m.length = 0)
    })
  }

  onBeforeUnmount(() => {
    clearError()
  })
  return {
    errorDestructionFunc,
    errorCell,
    clearError,
    isExistError,
    removeError,
  }
}
